<?php declare(strict_types=1);


namespace App\Api\V2\Controller\Glow;


use App\Api\Controllers\BaseController;
use App\Models\User;
use App\Traits\ResponseTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class IndexController extends BaseController
{

    use ResponseTrait;

    public function agent_level(Request $request)
    {
        session_start();
        $token = $this->parseToken();
        $store_id = $request->get('store_id', ''); // 门店id
        $company = $request->get('company', ''); //
        $model = $request->get('model', ''); //
        $user_id = DB::table('stores')->where(['store_id' => $store_id])->value('user_id'); // 门店的代理id
//        unset($_SESSION['users']);
        $users = $this->recursion($user_id, $token->user_id);
//        $users = $this->recursion(351, 1);
//        $users = json_decode($users, true);
//        $users = array_reverse($users);
        $configure_channel = DB::table('company_config')->where(['store_id' => $store_id, 'company' => $company])->first(); // 查找记录

        foreach ($users as $k => $v) {
            $rates = DB::table('user_rates')->where(['user_id' => $v['id'], 'company' => $company])->first();
            //通道
            $users_rate[$k]['agent_id'] = $v['id'];
            $users_rate[$k]['agency_cost'] = $rates->rate;
            $users_rate[$k]['rate_a'] = $rates->rate_a;
            $users_rate[$k]['rate_c'] = $rates->rate_c;
            $users_rate[$k]['rate_e'] = $rates->rate_e;
            $users_rate[$k]['rate_f'] = $rates->rate_f;
            $users_rate[$k]['rate_f_top'] = $rates->rate_f_top;


            //服务费
            $server_rate[$k]['agent_id'] = $v['id'];
            $server_rate[$k]['agency_cost'] = $rates->server_rate;

            //预充
            $yu_rate[$k]['agent_id'] = $v['id'];
            $yu_rate[$k]['agency_cost'] = $rates->yu_rate;

            //代扣
            $era_rate[$k]['agent_id'] = $v['id'];
            $era_rate[$k]['agency_cost'] = $rates->era_rate;
        }

        if ($configure_channel) {
            $configure_channel->users_rate = unserialize($configure_channel->users_rate);
            $configure_channel->daikou = $era_rate;
            $configure_channel->tongdao = $users_rate;
            $configure_channel->fuwufei = $server_rate;
            $configure_channel->yuchong = $yu_rate;
            $data = [
                'users_rate' => $users,
                'configure_channel' => $configure_channel,
            ];

            return json_encode([
                'status' => '2',
                'data' => $data
            ]);
        } else {
            $data = [
                'users_rate' => $users,
                'configure_channel' => [
                    'configure_channel_fee' => '0.00',
                    'channel_radio' => 1,
                    'model' => $model,
                    'money_level1' => '200',
                    'money_level2' => '100',
                    'money_level3' => '50',
                    'users_rate' => $users_rate,
                    'daikou' => $era_rate,
                    'fuwufei' => $server_rate,
                    'tongdao' => $users_rate,
                    'yuchong' => $yu_rate
                ],
            ];

            return json_encode([
                'status' => '1',
                'data' => $data
            ]);
        }
    }

    /**
     * 递归
     * 2022/09/06 16:07
     */
    public function recursion($user_id, $user_id_ding, $i = 0)
    {
        $data = [];
        $user = User::query()->where(['id' => $user_id])->select('id', 'name', 'pid')->first();
        if (empty($user)) {
            return $data;
        }
        $data[] = $user->toArray();
        if ($user->pid > 0 && $user->id != $user_id_ding) {
            $tmp = $this->recursion($user->pid, $user_id_ding, $i);
            $data = array_merge($data, $tmp);
        }
        return $data;
    }

    /**
     * 配置通道
     * 2022/09/06 14:39
     */
    function configure_channel(Request $request)
    {
        $token = $this->parseToken();
        session_start();

        $store_id = $request->get('store_id', '');
        $configure_channel_company = $request->get('configure_channel_company', '');


        //        headers["source"] = 'mini-p';
        $source = $request->header("source");
//        dd($source);
        if($source!="mini-p"){
            $pash = $request->path();
            $pass = $request->get('pass', '');
            $pass = substr(base64_decode($pass), 0, -5);
            $pass_verify = $this->pass_verify($pass, $pash); // 密钥验证
            $pass_verify = json_decode($pass_verify, true);
//        dd($pass,$pash,$pass_verify);
            if ($pass_verify['status'] == '1') {
                $pass_id = DB::table('pass')->where(['pass' => $pass])->value('id'); // 密钥id
                $remark = '门店配置通道: 门店id: ' . $store_id . '配置通道：' . $configure_channel_company;
                $this->operation_log($this->parseToken()->user_id, 6, $remark, $pass_id);
            } else {
                return $this->errorResponse("请联系中台给予权限-:".$source);
            }
        }


        $model = $request->get('model', ''); // 选择模式: 1: 服务费模式, 2: 代扣模式, 3: 通道扣费, 4: 预充模式

        $channel_radio = $request->get('channel_radio', '');
        $configure_channel_fee = $request->get('configure_channel_fee', '');
        $configure_channel_zfb = $request->get('configure_channel_zfb', '');
        $configure_channel_weixin = $request->get('configure_channel_weixin', '');
        $configure_channel_cloud = $request->get('configure_channel_cloud', '');
        $configure_channel_debit = $request->get('configure_channel_debit', '');
        $configure_channel_credit = $request->get('configure_channel_credit', '');

        /**
         * 新增逻辑
         */
        $rateConfig = [
            "rate_a" => $request->input("rate_a", 0),
            "rate_c" => $request->input("rate_c", 0),
            "rate_e" => $request->input("rate_e", 0),
            "rate_f" => $request->input("rate_f", 0),
            "rate_f_top" => $request->input("rate_f_top", 0)
        ];


        $money_level1 = $request->get('money_level1', '');
        $money_level2 = $request->get('money_level2', '');
        $money_level3 = $request->get('money_level3', '');
        $user_id = DB::table('stores')->where(['store_id' => $store_id])->value('user_id');
//        unset($_SESSION['users']);
        $users = $this->recursion1($user_id);
//        $users = json_decode($users, true);
//        $users = array_reverse($users);
        foreach ($users as $k => $v) {
            $rates = DB::table('user_rates')->where(['user_id' => $v['id'], 'company' => $configure_channel_company])->first();
            if ($model == 1) {
                if ($configure_channel_fee < $rates->server_rate) {
                    return $this->errorResponse("服务费费率不能低于渠道成本费率：" . $rates->server_rate);
                }
                $users_rate[$k] = array('agent_id' => $v['id'], 'agency_cost' => $rates->server_rate);
            } else if ($model == 2) {
                if ($configure_channel_fee < $rates->era_rate) {
                    return $this->errorResponse("代扣费率不能低于渠道成本费率：" . $rates->era_rate);
                }
                $users_rate[$k] = array('agent_id' => $v['id'], 'agency_cost' => $rates->era_rate);
            } else if ($model == 3) {
                if ($configure_channel_fee < $rates->rate) {
                    return $this->errorResponse("通道费率rate不能低于渠道成本费率：" . $rates->rate);
                }
                if ($rateConfig["rate_a"] < $rates->rate_a) {
                    return $this->errorResponse("通道扣费rate_a不能低于渠道成本费率：" . $rates->rate_a);
                }
                if ($rateConfig["rate_c"] < $rates->rate_c) {
                    return $this->errorResponse("通道扣费rate_c不能低于渠道成本费率：" . $rates->rate_c);
                }
                if ($rateConfig["rate_e"] < $rates->rate_e) {
                    return $this->errorResponse("通道扣费rate_e不能低于渠道成本费率：" . $rates->rate_e);
                }
                if ($rateConfig["rate_f"] < $rates->rate_f) {
                    return $this->errorResponse("通道扣费rate_f不能低于渠道成本费率：" . $rates->rate_f);
                }
                $users_rate[$k] = array('agent_id' => $v['id'], 'agency_cost' => $rates->rate);
            } else if ($model == 4) {
                if ($configure_channel_fee < $rates->yu_rate) {
                    return $this->errorResponse("预充费率不能低于渠道成本费率：" . $rates->yu_rate);
                }
                $users_rate[$k] = array('agent_id' => $v['id'], 'agency_cost' => $rates->yu_rate);
            }
        }
        if ($channel_radio == 1) {
            if ($configure_channel_fee == '') {
                return $this->errorResponse("请输入商户扣费费率");
            }
            $data = [
                'store_id' => $store_id,
                'model' => $model,
                'company' => $configure_channel_company,
                'users_rate' => serialize($users_rate),
                'channel_radio' => $channel_radio,
                'configure_channel_fee' => $configure_channel_fee,
                'money_level1' => $money_level1,
                'money_level2' => $money_level2,
                'money_level3' => $money_level3,
                'create_time' => time(),
                'update_time' => time(),
            ];

        } else {
            if ($configure_channel_zfb == '' || $configure_channel_weixin == '' || $configure_channel_cloud == '' || $configure_channel_debit == '' || $configure_channel_credit == '') {
                return $this->errorResponse("请填写完整");
            }
            $data = [
                'store_id' => $store_id,
                'model' => $model,
                'company' => $configure_channel_company,
                'users_rate' => serialize($users_rate),
                'channel_radio' => $channel_radio,
                'configure_channel_zfb' => $configure_channel_zfb,
                'configure_channel_weixin' => $configure_channel_weixin,
                'configure_channel_cloud' => $configure_channel_cloud,
                'configure_channel_debit' => $configure_channel_debit,
                'configure_channel_credit' => $configure_channel_credit,
                'money_level1' => $money_level1,
                'money_level2' => $money_level2,
                'money_level3' => $money_level3,
                'create_time' => time(),
                'update_time' => time(),
            ];
        }
        $server_stores = DB::table('server_stores')->where('store_id', $store_id)
            ->where("company",$configure_channel_company)
            ->first();
        $store = DB::table('stores')->where('store_id', $store_id)->first();
        if ($model == 4) {
            //预充
            DB::table('stores')->where(['store_id' => $store_id])->update(['rata_status' => 1, 'rata_store' => $configure_channel_fee]);
            if (empty($server_stores)) {
                DB::table('server_stores')->insert(
                    array(
                        'store_id' => $store_id,
                        'status' => 0,
                        'rata_store' => $configure_channel_fee,
                        'store_name' => $store->store_name,
                        'money_level1' => $money_level1,
                        'money_level2' => $money_level2,
                        'money_level3' => $money_level3,
                        'created_at' => date('Y-m-d', 0),
                        'company' => $configure_channel_company,
                    )
                );
            }
            $all_pay_ways = DB::table('store_ways_desc')->where('company', $configure_channel_company)->get();
            $ways = DB::table('store_pay_ways')->where('store_id', $store_id)->where('company', $configure_channel_company)->first();
            if ($ways) {
                DB::table('store_pay_ways')->where('store_id', $store_id)
                    ->where('company', $configure_channel_company)
                    ->update([
                        'rate' => $configure_channel_fee,
                        "rate_a" => $rateConfig["rate_a"],
                        "rate_c" => $rateConfig["rate_c"],
                        "rate_e" => $rateConfig["rate_e"],
                        "rate_f" => $rateConfig["rate_f"],
                        "rate_f_top" => $rateConfig["rate_f_top"]
                    ]);
            } else {
                foreach ($all_pay_ways as $k => $v) {
                    $gets = DB::table('store_pay_ways')->where('store_id', $store_id)->where('ways_source', $v->ways_source)->get();
                    $count = count($gets);
                    $data1 = [
                        'store_id' => $store_id,
                        'ways_type' => $v->ways_type,
                        'company' => $v->company,
                        'ways_source' => $v->ways_source,
                        'ways_desc' => $v->ways_desc,
                        'sort' => ($count + 1),
                        'rate' => $configure_channel_fee,
                        "rate_a" => $rateConfig["rate_a"],
                        "rate_c" => $rateConfig["rate_c"],
                        "rate_e" => $rateConfig["rate_e"],
                        "rate_f" => $rateConfig["rate_f"],
                        "rate_f_top" => $rateConfig["rate_f_top"],
                        'settlement_type' => $v->settlement_type,
                        'status' => 3,
                        'status_desc' => '未开通',
                    ];
                    $res = DB::table('store_pay_ways')->insert($data1);
                }
            }
        } else if ($model == 3) {
            $all_pay_ways = DB::table('store_ways_desc')->where('company', $configure_channel_company)->get();
            $ways = DB::table('store_pay_ways')->where('store_id', $store_id)->where('company', $configure_channel_company)->first();
            if ($ways) {
                DB::table('store_pay_ways')->where('store_id', $store_id)->where('company', $configure_channel_company)->update([
                    'rate' => $configure_channel_fee,
                    "rate_a" => $rateConfig["rate_a"],
                    "rate_c" => $rateConfig["rate_c"],
                    "rate_e" => $rateConfig["rate_e"],
                    "rate_f" => $rateConfig["rate_f"],
                    "rate_f_top" => $rateConfig["rate_f_top"],
                ]);
            } else {
                foreach ($all_pay_ways as $k => $v) {
                    $gets = DB::table('store_pay_ways')->where('store_id', $store_id)->where('ways_source', $v->ways_source)->get();
                    $count = count($gets);
                    $data1 = [
                        'store_id' => $store_id,
                        'ways_type' => $v->ways_type,
                        'company' => $v->company,
                        'ways_source' => $v->ways_source,
                        'ways_desc' => $v->ways_desc,
                        'sort' => ($count + 1),
                        'rate' => $configure_channel_fee,
                        "rate_a" => $rateConfig["rate_a"],
                        "rate_c" => $rateConfig["rate_c"],
                        "rate_e" => $rateConfig["rate_e"],
                        "rate_f" => $rateConfig["rate_f"],
                        "rate_f_top" => $rateConfig["rate_f_top"],
                        'settlement_type' => $v->settlement_type,
                        'status' => 3,
                        'status_desc' => '未开通',
                    ];
                    $res = DB::table('store_pay_ways')->insert($data1);
                }
            }
        } else if ($model == 2) {
            $all_pay_ways = DB::table('store_ways_desc')->where('company', $configure_channel_company)->get();
            $ways = DB::table('store_pay_ways')->where('store_id', $store_id)->where('company', $configure_channel_company)->first();
            if ($ways) {
                DB::table('store_pay_ways')->where('store_id', $store_id)->where('company', $configure_channel_company)->update([
                    'rate' => $configure_channel_fee,
                    "rate_a" => $rateConfig["rate_a"],
                    "rate_c" => $rateConfig["rate_c"],
                    "rate_e" => $rateConfig["rate_e"],
                    "rate_f" => $rateConfig["rate_f"],
                    "rate_f_top" => $rateConfig["rate_f_top"],
                ]);
            } else {
                foreach ($all_pay_ways as $k => $v) {
                    $gets = DB::table('store_pay_ways')->where('store_id', $store_id)->where('ways_source', $v->ways_source)->get();
                    $count = count($gets);
                    $data1 = [
                        'store_id' => $store_id,
                        'ways_type' => $v->ways_type,
                        'company' => $v->company,
                        'ways_source' => $v->ways_source,
                        'ways_desc' => $v->ways_desc,
                        'sort' => ($count + 1),
                        'rate' => $configure_channel_fee,
                        "rate_a" => $rateConfig["rate_a"],
                        "rate_c" => $rateConfig["rate_c"],
                        "rate_e" => $rateConfig["rate_e"],
                        "rate_f" => $rateConfig["rate_f"],
                        "rate_f_top" => $rateConfig["rate_f_top"],
                        'settlement_type' => $v->settlement_type,
                        'status' => 3,
                        'status_desc' => '未开通',
                    ];
                    $res = DB::table('store_pay_ways')->insert($data1);
                }
            }
        } else if ($model == 1) {
            DB::table('stores')->where(['store_id' => $store_id])->update(['rata_status' => 1, 'rata_store' => $configure_channel_fee]);
            $all_pay_ways = DB::table('store_ways_desc')->where('company', $configure_channel_company)->get();
            $ways = DB::table('store_pay_ways')->where('store_id', $store_id)->where('company', $configure_channel_company)->first();
            if ($ways) {
                DB::table('store_pay_ways')->where('store_id', $store_id)->where('company', $configure_channel_company)->update([
                    'rate' => $configure_channel_fee,
                    "rate_a" => $rateConfig["rate_a"],
                    "rate_c" => $rateConfig["rate_c"],
                    "rate_e" => $rateConfig["rate_e"],
                    "rate_f" => $rateConfig["rate_f"],
                    "rate_f_top" => $rateConfig["rate_f_top"],
                ]);
            } else {
                foreach ($all_pay_ways as $k => $v) {
                    $gets = DB::table('store_pay_ways')->where('store_id', $store_id)->where('ways_source', $v->ways_source)->get();
                    $count = count($gets);
                    $data1 = [
                        'store_id' => $store_id,
                        'ways_type' => $v->ways_type,
                        'company' => $v->company,
                        'ways_source' => $v->ways_source,
                        'ways_desc' => $v->ways_desc,
                        'sort' => ($count + 1),
                        'rate' => $configure_channel_fee,
                        "rate_a" => $rateConfig["rate_a"],
                        "rate_c" => $rateConfig["rate_c"],
                        "rate_e" => $rateConfig["rate_e"],
                        "rate_f" => $rateConfig["rate_f"],
                        "rate_f_top" => $rateConfig["rate_f_top"],
                        'settlement_type' => $v->settlement_type,
                        'status' => 3,
                        'status_desc' => '未开通',
                    ];
                    $res = DB::table('store_pay_ways')->insert($data1);
                }
            }
        }
        $configure_channel = DB::table('company_config')->where(['store_id' => $store_id, 'company' => $configure_channel_company])->first(); // 查找记录
        if ($configure_channel) {
            unset($data['create_time']);
            $data['update_time'] = time();
            $res = DB::table('company_config')->where(['id' => $configure_channel->id])->update($data);
        } else {
            $res = DB::table('company_config')->insert($data);
        }
        if ($res) {
            return $this->successResponse("配置成功");
        } else {
            return $this->successResponse("网络错误");
        }
    }


    /**
     * 递归
     * 2022/09/06 16:07
     */
    public function recursion1($user_id)
    {
        $data = [];
        $user = User::query()->where(['id' => $user_id])->select('id', 'name', 'pid')->first();
        if (empty($user)) {
            return $data;
        }
        $data[] = $user->toArray();
        if ($user->pid > 0) {
            $tmp = $this->recursion1($user->pid);
            $data = array_merge($data, $tmp);
        }
        return $data;
    }

}
